import { isObject } from "lodash-es"
//去除请求参数中前后空格
export function trimRequestParams(params) {
  if (Array.isArray(params)) {
    return params.map((item) => trimRequestParams(item))
  }

  if (isObject(params)) {
    const result = {}
    for (const key of Object.keys(params)) {
      const value = params[key]
      if (typeof value === "string") {
        result[key] = value.trim()
      } else if (Array.isArray(value)) {
        result[key] = value.map((item) => trimRequestParams(item))
      } else if (isObject(value)) {
        result[key] = trimRequestParams(value)
      } else {
        result[key] = value
      }
    }
    return result
  }

  return params
}
//过滤对象中的空字段
export function filterProps(origin){
  return Object.keys(origin)
      .filter(key => origin[key] !== undefined && origin[key] !== null && origin[key] !== '')
      .reduce((acc, key) => ({
        ...acc,
        [key]: origin[key]
      }), {});
}

type FlattenObject<U> = U extends object ? { [K in keyof U as string]: U[K] extends object ? FlattenObject<U[K]> : U[K] } : U;
//后端返回数据扁平化
export function flattenObject(obj: Record<string, any>, prefix = ''): Record<string, any> {
  return Object.keys(obj).reduce((acc, key) => {
    const pre = prefix.length ? prefix + '.' : '';
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
      Object.assign(acc, flattenObject(obj[key], pre + key));
    } else {
      acc[pre + key] = obj[key];
    }
    return acc;
  }, {} as Record<string, any>);
}
export function getNestedValue(obj, path, defaultValue = undefined) {
  // 将路径按点分割成数组
  const keys = path.split('.');
  let result = obj;

  // 遍历每个键，深入对象的每一层
  for (let key of keys) {
    if (result[key] === undefined) {
      // 如果在任何一层找不到对应的键，则返回默认值
      return defaultValue;
    }
    result = result[key];
  }

  // 返回最终的结果或默认值
  return result !== undefined ? result : defaultValue;
}

